import React from 'react';
import { connect } from 'react-redux';
import { Toast, Card, ActionSheet, Modal } from 'antd-mobile-v2';
import { ConnectProps } from 'typings/connect';
import { GaeaRender as Render } from '@/plugins/form/form-render/render/render.component';
import PCComponents from '@/plugins/form/form-components/index';
import createDOMForm from '@/components/rc-form/createDOMForm';
import { WrappedFormClass } from 'rc-form';
import {
  GetRucApplyDetail,
  GetRucDraftDetail,
  GetRucDraftAudit,
  DelRucDraft,
  doUrging,
  isUrging
} from '@/services/laber-declare';
import styles from './index.module.less';
import { IGaeaAll } from '@/plugins/form/types';
import { parseFormData, parseValueForDetail, parseValue } from '@/plugins/form/form-render/utils/detail-parser';
import { BPMN_APPLY_NODE_ID } from '@/plugins/constant';
import { SUCCESS_CODE } from '@/services/constant';
import { setTaskAction } from '@/services/approval';
import {
  isCheckedAuth,
  sendVerificationCode,
  checkVerificationCode
} from '@/services/commons';
import ProcessSteps, {
  ProcessValidator,
  ProcessValidateResult
} from '@/components/ProcessSteps';
import ConfirmAndRefuseModal from '@/components/ConfirmAndRefuseModal';
import memoize from 'memoize-one';
import Avatar from '@/components/avatar';
import classnames from 'classnames';
import ButtonFooterDetail from '@/components/button-footer-detail';
import {
  ApprovalColor,
  APPROVAL_STATUS_NAME,
  APPROVAL_STATUS,
  ProcessActions,
  PDF_File_TYPE,
  ZHIDAN_STATUS_NAME,
  ZHIDAN_STATUS
} from '../constants';
import { ColumnText } from '@/plugins/form/form-components/column-text/view';
// import Log from '../components/log';
import { applyType } from '@/constants';
import history from '@/utils/history';
import ProcessList from '@/components/ProcessList';
import VerificationCodeModal from '@/components/verification-code-modal';
import PreviewPdf from '@/components/preview-pdf';


interface IApprovalModal
  extends ConnectProps<any, any, { innerProcDefId: string; title: string }> {
  form?: WrappedFormClass<{}>;
  loading?: boolean;
  userInfo?: any;
}

interface IApprovalState {
  detailLoading?: boolean;
  formData: string;
  formShowData?: IGaeaAll | null;
  formValues?: IterateAny | null;
  historyTaskList: any;
  detailData?: any;
  loading: boolean;
  modalObj?: any;
  modalVisible?: boolean;
  [propName: string]: any;
}

enum OptType {
  waitDeclare = '1', // 待审批
  hasDeclare = '2' // 已审批
}

// interface DetailItem {
//   innerProcDefId: string;
//   applyName: string;
//   procRecordId: string;
//   applyId: string;
//   applyType: string;
//   applyUserId: string;
//   crtTime: string;
//   id: string;
//   handler: string;
//   procStatus: number;
//   [propName: string]: any;
// }

enum OperationsObj {
  CONFIRM = '0004',
  REFUSE = '0007'
}

class ApprovalModal extends React.Component<IApprovalModal, IApprovalState> {
  processValidator: ProcessValidator;
  submitType: string;
  isAction: boolean;
  constructor(props: IApprovalModal) {
    super(props);
    this.isAction = false;
    this.state = {
      detailLoading: false,
      formData: '',
      formShowData: null,
      formValues: null,
      historyTaskList: [],
      detailData: null,
      loading: false,
      modalObj: {}, // 同意/拒绝的弹窗格式
      modalVisible: false, // 同意/拒绝的弹窗显示隐藏
      verificationCodeModalVisible: false, // 短信验证码弹窗显隐
      needMessageCheck: false, // 审批时是否需要短信验证
      previewPdfVisible: false,
      pdfUrl: ''
    };
  }

  componentDidMount() {
    this.pageInit();
  }
  componentWillUnmount(){
    this.setState = () => {
      return false;
    };
  }
  pageInit = () => {
    const applyId = this.getSearchName('applyId'); // this.props.location?.query?.procRecordId;
    const procRecordId = this.getSearchName('procRecordId'); // this.props.location?.query?.procRecordId;
    const status = Number(this.getSearchName('status'));
    const applyType = this.getSearchName('applyType');
    if (!applyId) return;
    // if (status === APPROVAL_STATUS.Draft) {
    //   this.getDataDetail(applyId); // 草稿修改
    // } else if (status !== APPROVAL_STATUS.Draft) {
    //   const param = {
    //     applyType: applyType,
    //     dataId: applyId,
    //     procRecordId: procRecordId
    //   };
    //   this.getDataAudit(param); // 审批中详情
    // }

    // 目前没有草稿状态
    const param = {
      applyType: applyType,
      dataId: applyId,
      procRecordId: procRecordId
    };
    this.getDataAudit(param); // 审批中详情
    this.checkMessageAuth();
  };

  // 草稿详情
  getDataDetail = async (id: string) => {
    const res: any = await GetRucDraftDetail(id);
    if (res && res.status == SUCCESS_CODE) {
      if (!res.data?.processListRes?.formData) return;
      const {
        formModelData,
        formValues,
        choosePersons
      } = res.data?.processListRes?.formData;
      this.props.form && this.props.form.setFormExtranalData(res.data);
      const detailData = {
        bizCrtTime: res.data?.bizCrtTime,
        bizCode: res.data?.bizCode,
        bizUserName: res.data?.bizUserName,
        bizOrgName: res.data?.bizOrgName,
        procStatusName: res.data?.procStatusName,
        bizStatus: res.data?.bizStatus,
        status: res.data?.status,
        dataId: res.data?.dataId,
        innerProcDefId: res.data?.innerProcDefId,
        id: res.data?.id,
        serialNumber: res.data?.serialNumber,
        bizOrgId: res.data?.bizOrgId,
        srvTime: res.srvTime
      };
      // 合并值和json
      // let formParsed = parseFormData(
      //   formModelData,
      //   'all',
      //   true
      // );
      let formParsed = parseFormData(formModelData, BPMN_APPLY_NODE_ID);
      const formValuesS = parseValue(formValues);
      // 将formValues的key，转换成formItem的key
      formParsed = parseValueForDetail(formParsed, formValuesS);

      this.setState({
        formValues: {
          attachmentList: res.data.attachmentList || [],
          ...formParsed
        },
        formData: formModelData,
        formShowData: parseFormData(formModelData, BPMN_APPLY_NODE_ID),
        detailData: detailData,
        choosePersons: choosePersons
      });
    }
  };

  // 审批中详情
  getDataAudit = async (id: object) => {
    const res: any = await GetRucApplyDetail(id);
    console.log('res---{}',res);
    if (res && res.status == SUCCESS_CODE) {
      if (!res.data?.formData) return;
      const {
        formModelData,
        formValues,
        choosePersons
      } = res.data?.formData;
      this.props.form && this.props.form.setFormExtranalData(res.data);
      const detailData = {
        bizCrtTime: res.data?.bizCrtTime,
        bizCode: res.data?.bizCode,
        bizUserName: res.data?.formData?.startName,
        bizOrgName: res.data?.bizOrgName,
        bizUserId: res.data?.formData?.startUserId,
        procStatusName: res.data?.procStatusName,
        bizStatus: res.data?.bizStatus,
        dataId: res.data?.dataId,
        innerProcDefId: res.data?.innerProcDefId,
        procRecordId: res.data?.procRecordId,
        procInstId: res.data?.procInstId,
        procName: res.data?.procName,
        procNo: res.data?.procNo,
        historyTask: res.data.historyTask,
        bizOrgId: res.data?.bizOrgId,
        srvTime: res.srvTime,
        serialNumber: res.data?.serialNumber,
        actualHairAmount: res.data?.actualHairAmount,
        taxAmount: res.data?.taxAmount,
        msg: res.data?.msg,
        zhiDanState: res.data?.zhiDanState
      };

      // 合并值和json
      // let formParsed = parseFormData(
      //   formModelData,
      //   'all',
      //   true
      // );
      let formParsed = parseFormData(formModelData, BPMN_APPLY_NODE_ID);
      const formValuesS = parseValue(formValues);
      // 将formValues的key，转换成formItem的key
      formParsed = parseValueForDetail(formParsed, formValuesS);
      // console.log('formValues：',formValues);
      console.log('formValues：',formValuesS);

      this.setState({
        formValues: {
          attachmentList: res.data.attachmentList || [],
          ...formParsed
        },
        formData: formModelData,
        formShowData: parseFormData(formModelData, BPMN_APPLY_NODE_ID),
        detailData: detailData,
        choosePersons: choosePersons
      });
    }
  };

  getSearchName = (name?: string) => {
    const locationStr = this.props.location?.search?.split('?')?.[1];
    const arr = locationStr?.split('&');
    const obj: any = {};
    for (let i = 0; i < arr?.length; i++) {
      const aItem = arr[i]?.split('=');
      obj[aItem[0]] = decodeURIComponent(aItem[1]);
    }
    return name ? obj?.[name] || '' : obj;
  };

  getButtonOptions = () => {
    const deleteBtn = {
      text: '删除',
      icon: <i className="iconfont icon">&#xe6e0;</i>,
      onClick: this.handleDelete
    };
    const editBtn = {
      text: '修改',
      icon: <i className="iconfont icon">&#xe6ea;</i>,
      onClick: () => this.handleEdit('edit')
    };
    const publishBtn = {
      text: '提交',
      icon: <i className="iconfont icon">&#xe6e9;</i>,
      loading: this.state.loading,
      onClick: this.handlePublish
    };
    const revertBtn = {
      text: '撤销',
      icon: <i className="iconfont icon">&#xe713;</i>,
      onClick: this.handleRevert
    };
    const reSubmitBtn = {
      text: '重新提交',
      icon: <i className="iconfont icon">&#xe6e9;</i>,
      onClick: this.handleReSubmit
    };
    const urging = {
      text: '催办',
      icon: <i className="iconfont icon">&#xe716;</i>,
      onClick: this.handleUrging
    };
    const rejectBtn = {
      text: '拒绝',
      icon: <i className="iconfont icon">&#xe717;</i>,
      onClick: this.handleRefuse
    };
    const acceptBtn = {
      text: '同意',
      icon: <i className="iconfont icon">&#xe718;</i>,
      onClick: this.handleOK
    };
    const optType: OptType = this.getSearchName('type');
    console.log('optType======{}',optType);
    const bizStatus = this.state.detailData?.bizStatus;
    const bizUserId = this.state.detailData?.bizUserId;
    const taskRecordId = this.getSearchName('applyId');
    if (optType === OptType.waitDeclare) {
      // 从待审批进入时
      return [rejectBtn, acceptBtn];
    }
    // 已撤销状态的申报
    if (
      bizStatus === APPROVAL_STATUS.Revert ||
      bizStatus === APPROVAL_STATUS.Reject
    ) {
      return [reSubmitBtn];
    }
    // 草稿状态的申报
    if (bizStatus === APPROVAL_STATUS.Draft) {
      return [deleteBtn, editBtn, publishBtn];
    }
    // 审批状态的申报
    if (!taskRecordId) {
      // 从待审批列表进来时才会有taskRecordId，没有的话说明是从其他入口进去。此时不支持审批操作
      return [];
    }
    if (bizStatus === APPROVAL_STATUS.Approvaling) {
      const selfUserId = this.props.userInfo?.userId;
      if (bizUserId === selfUserId) {
        // 提交人是自己
        return [revertBtn, reSubmitBtn, urging];
      }
      // return [rejectBtn, acceptBtn];
    }
    return [];
  };

  recall = async () => {
    const params: any = {
      action: ProcessActions.Recall,
      procRecordId: this.state.detailData?.procRecordId
    };
    if (this.props.dispatch) {
      const res = await this.props.dispatch({
        type: 'capproval/changeMyApplyProcess',
        payload: params
      });
      if (res && res.status === SUCCESS_CODE) {
        return true;
      } else {
        Toast.fail(res?.message);
      }
    }
    return false;
  };

  // 显示我的发起-撤销确认模态框
  handleRevert = () => {
    const BUTTONS = ['确认', '取消'];
    ActionSheet.showActionSheetWithOptions(
      {
        options: BUTTONS,
        cancelButtonIndex: BUTTONS.length - 1,
        destructiveButtonIndex: BUTTONS.length - 2,
        message: '确认撤销此申请？',
        maskClosable: false
      },
      async (buttonIndex) => {
        if (buttonIndex === 0) {
          if (!this.isAction) {
            this.isAction = true;
            const isSuccess = await this.recall();
            this.isAction = false;
            if (isSuccess) {
              Toast.success('撤销成功');
              this.props.history?.goBack();
            }
          }
        }
      }
    );
  };

  handleReSubmit = () => {
    const status = this.state.detailData?.bizStatus;
    if (
      status === APPROVAL_STATUS.Revert ||
      status === APPROVAL_STATUS.Reject
    ) {
      this.handleEdit('resubmit');
    }
    const BUTTONS = ['确认', '取消'];
    ActionSheet.showActionSheetWithOptions(
      {
        options: BUTTONS,
        cancelButtonIndex: BUTTONS.length - 1,
        destructiveButtonIndex: BUTTONS.length - 2,
        message: '重新提交后，当前申请将自动撤销，确定继续?',
        maskClosable: false
      },
      async (buttonIndex) => {
        if (buttonIndex === 0) {
          if (!this.isAction) {
            this.isAction = true;
            const isSuccess = await this.recall();
            this.isAction = false;
            if (isSuccess) {
              Toast.success('撤销成功，可重新提交');
              this.handleEdit('resubmit');
            }
          }
        }
      }
    );
  };

  handleDelete = async () => {
    const titleD = decodeURIComponent(this.getSearchName('title'));
    const BUTTONS = ['确认', '取消'];
    ActionSheet.showActionSheetWithOptions(
      {
        options: BUTTONS,
        cancelButtonIndex: BUTTONS.length - 1,
        destructiveButtonIndex: BUTTONS.length - 2,
        message: `确认删除${titleD}?`,
        maskClosable: false
      },
      async (buttonIndex) => {
        if (buttonIndex === 0) {
          if (!this.isAction) {
            this.isAction = true;
            const res: {
              status?: number;
              message?: string;
            } = await DelRucDraft(this.state.detailData?.dataId);
            if (res?.status == 200) {
              Toast.success(res?.message);
              this.props.history?.goBack();
            } else {
              Toast.fail(res?.message || '删除失败');
            }
            this.isAction = false;
          }
        }
      }
    );
  };

  handleUrging = async () => {
    const BUTTONS = ['确认', '取消'];
    const { detailData } = this.state;
    const value = detailData.historyTask?.find(
      (item: any) => item.nodeStatus == 0
    );
    const params = {
      innerProcDefId: detailData.innerProcDefId,
      procInstId: detailData.procInstId,
      procName: detailData.procName,
      procNo: detailData.procNo,
      taskDefKey: value?.taskDefKey
    };
    const res: { status?: number; message?: string } = await isUrging(params);
    if (res && res.status == 200) {
      ActionSheet.showActionSheetWithOptions(
        {
          options: BUTTONS,
          cancelButtonIndex: BUTTONS.length - 1,
          destructiveButtonIndex: BUTTONS.length - 2,
          message: '确定催办?',
          maskClosable: false
        },
        async (buttonIndex) => {
          if (buttonIndex === 0) {
            const result: {
              status?: number;
              message?: string;
            } = await doUrging(params);
            if (result.status == 200) {
              Toast.success('催办成功');
            } else {
              Toast.fail(result?.message);
            }
          }
        }
      );
    } else {
      Toast.fail(res?.message);
    }
  };

  //操作同意
  handleOK = () => {
    this.confirmHandle('0004');
  };

  //操作拒绝
  handleRefuse = () => {
    this.confirmHandle('0007');
  };

  checkMessageAuth = async () => {
    const needSign = Number(this.getSearchName('needSign'));
    // mock
    // needSign = 1;
    // mock end
    if (!needSign) return;
    const res = await isCheckedAuth();
    if (!res.data) {
      this.setState({
        needMessageCheck: true
      });
    }
  };

  confirmHandle = (type: string) => {
    const item: any = {
      id: this.getSearchName('taskRecordId')
    };
    const { needMessageCheck } = this.state;
    if (needMessageCheck) {
      this.setState({
        verificationCodeModalVisible: true
      });
    }
    const applyName = decodeURIComponent(this.getSearchName('title'));
    if (type === OperationsObj.CONFIRM) {
      this.setState({
        modalObj: {
          btnWord: '确认同意',
          opreationTitle: `确定同意${applyName}${applyName && applyName.includes('申请') ? '吗？' : '申请吗？'
          }`,
          placeholder: '请输入审批意见（必填）',
          opreationType: type,
          detailItem: item
        }
      });
    } else {
      this.setState({
        modalObj: {
          btnWord: '确认拒绝',
          opreationTitle: `确定拒绝${applyName}${applyName && applyName.includes('申请') ? '吗？' : '申请吗？'
          }`,
          placeholder: '请输入审批意见（必填）',
          opreationType: type,
          detailItem: item
        }
      });
    }
    this.setState({ modalVisible: true });
  };

  handleVerificationClose = () => {
    this.setState({
      verificationCodeModalVisible: false,
      modalVisible: false
    });
  };

  handleVerifiSuccess = () => {
    this.setState({
      verificationCodeModalVisible: false
    });
  };

  doClose = (val: boolean) => {
    this.setState({ modalVisible: val });
  };

  doSubmit = (val: boolean, word: string) => {
    this.modalOk(word, val);
  };

  // 弹框确认
  modalOk = async (formVal: string, show: boolean) => {
    const { modalObj } = this.state;
    const params = {
      action: modalObj?.opreationType,
      taskRecordId: modalObj?.detailItem?.id as string,
      handlerComment: formVal
    };
    try {
      const res: any = await setTaskAction(params);
      if (res.status == 200) {
        Toast.success('操作成功');
        this.setState({ modalVisible: show }, () => {
          this.props.history?.goBack();
        });
      } else {
        Toast.success(res.message);
      }
    } catch (error) {
      console.log(error);
    }
  };

  handleEdit = (type) => {
    const { detailData } = this.state;
    const titleE = this.getSearchName('title');
    // const applyId = this.getSearchName('applyId');
    const applyTypeFromUrl =
      this.getSearchName('applyType') || applyType.STUDENT_LABOUR_APPLY;
    if (type == 'edit') {
      history?.push({
        pathname: '/resubmit',
        query: {
          applyType: applyTypeFromUrl,
          applyId: detailData?.dataId,
          innerProcDefId: detailData?.innerProcDefId,
          status: detailData?.bizStatus,
          resubmit: false,
          title: titleE,
          orgId: detailData?.bizOrgId
        }
      });
    } else if (type == 'resubmit') {
      history?.push({
        pathname: '/resubmit',
        query: {
          applyType: applyTypeFromUrl,
          applyId: detailData?.dataId,
          innerProcDefId: detailData?.innerProcDefId,
          status: APPROVAL_STATUS.Revert,
          resubmit: true,
          title: titleE,
          procRecordId: detailData?.procRecordId,
          orgId: detailData?.bizOrgId
        }
      });
    }
  };

  handlePublish = async () => {
    const props = this.props;
    const state = this.state;
    const applyId = this.getSearchName('applyId');
    const applyName = this.getSearchName('title');
    let values: any = null;
    let extra: any = {};
    const FormExtraData = props?.form?.getFormExtranalData() || {};

    if (this.props.form && this.props.form.submitCallback) {
      const res = await this.props.form.submitCallback();
      values = await this.props.form?.validateFields(() => {
        // do nothing
      });
      values = state.formValues;
      extra = res.data.extra;
    }
    if (!values) {
      values = state.formValues;
    }

    // 校验申报总额
    const { userId } = this.props.userInfo;
    /**
     * userId 当前申报人id
     * principalCode 关联项目负责人id
     * projectBalance 项目余额
     * authorizeAmountUsable 可用授权金额
     * authorizeAmount 授权金额
     * matterTotalUseAble 事项余额
     * totalAmount 申报总额
     */
    try {
      let {
        principalCode,
        projectBalance,
        authorizeAmountUsable,
        authorizeAmount
      } = values.projectId || {};
      authorizeAmount = authorizeAmount == -1 ? Infinity : authorizeAmount;

      const { totalAmount } = values;
      let matterTotalUseAble;
      // 关联事项非必选不判断事项余额
      if (!values.relatedMattersAddList?.value?.length) {
        matterTotalUseAble = Infinity;
      } else {
        // 有不限额不判断
        if (
          values.relatedMattersAddList.value.find(
            (item: any) => item.matterTotalUseAble === -1
          )
        ) {
          matterTotalUseAble = Infinity;
        } else {
          matterTotalUseAble = values.relatedMattersAddList.value.reduce(
            (pre: number, next: any) => pre + next.matterTotalUseAble,
            0
          );
        }
      }
      // 先不判断可用授信额度 authorizeAmountUsable
      const minNum =
        userId === principalCode
          ? Math.min(projectBalance, matterTotalUseAble)
          : Math.min(projectBalance, matterTotalUseAble, authorizeAmount);

      const obj = {
        [projectBalance]: '项目余额',
        [matterTotalUseAble]: '事项余额',
        [authorizeAmount]: '授权金额'
        // [authorizeAmountUsable]: '可用授权金额'
      };
      if (totalAmount > minNum) {
        return Toast.fail(`申报总额不得超过${obj[minNum]}。`);
      }

      if (userId !== principalCode) {
        if (
          totalAmount > authorizeAmountUsable &&
          authorizeAmountUsable != -1
        ) {
          // return Toast.fail('申报总额不得超过可用授权金额。');
        }
      }
    } catch (e) {
      console.log(e);
    }

    let processValidateResult: ProcessValidateResult = {} as ProcessValidateResult;
    if (this.processValidator) {
      processValidateResult = this.processValidator();
      if (!processValidateResult.result) {
        Toast.fail(processValidateResult.message);
        return;
      }
    }
    if (this.props.dispatch) {
      const applyTypeFromUrl = this.getSearchName('applyType');
      this.setState({
        loading: true
      });
      this.props
        .dispatch({
          type: 'capproval/startProcess',
          payload: {
            applyType: applyTypeFromUrl || 'STOCK_RECEIVE_APPLY',
            applyName,
            submitFlag: 1,
            forms: {
              formModelData: state.formData,
              formValues: JSON.stringify(values)
            },
            innerProcDefId: FormExtraData?.innerProcDefId,
            choosePersons:
              processValidateResult.value || state.choosePersons
                ? JSON.parse(state.choosePersons)
                : [],
            ...(extra ? extra : {}),
            dataId: applyId // 提交时的 dataId 使用原来的 applyId，写在后面防止覆盖
          }
        })
        .then((res?: any) => {
          this.setState({
            loading: false
          });
          if (res && res.status == 200) {
            Toast.success('提交成功');
            this.props.history?.goBack();
          } else {
            Toast.fail(res?.message);
          }
        })
        .catch((e: any) => {
          console.log(e);
          this.setState({
            loading: false
          });
        });
    }
  };

  public setValidateMethod = memoize((mth?: ProcessValidator) => {
    this.processValidator = mth;
  });

  // 预览pdf
  previewPDF = async () => {
    const { formValues } = this.state;
    // const id = formValues.attachmentList[0].id;
    let stampObj;
    if (!formValues.attachmentList) return;
    stampObj = formValues.attachmentList.find(
      (item: any) => item.fileType === PDF_File_TYPE
    );
    history?.push({
      pathname: `/previewPdf/${stampObj.id}`
    });
    // const res = await GetFileUrl({ id, device: 'H5' });
    // this.setState({ pdfUrl: res.data, previewPdfVisible: true });
  };
  // 检查是否存在pdf电子签章
  checkPDFIsExit = () => {
    const { formValues } = this.state;
    return formValues?.attachmentList?.some((ele) => {
      return ele.fileType === PDF_File_TYPE;
    });
  };
  renderForm = () => {
    const { state, props } = this;
    if (props.form && state.formData && state.formValues) {
      return (
        <Render
          renderMode="detail"
          form={props.form}
          formValues={this.state.formValues}
          value={this.state.formShowData}
          componentClasses={PCComponents}
        />
      );
    } else {
      return null;
    }

  }
  render() {
    const props = this.props;
    const state = this.state;
    const {
      modalVisible,
      modalObj,
      verificationCodeModalVisible,
      previewPdfVisible,
      pdfUrl,
      detailData
    } = this.state;
    const title = detailData?.procName; //  || decodeURIComponent(this.getSearchName('title'));
    const buttonOptions = this.getButtonOptions();
    const modalProps = {
      topTitle: '审批意见',
      modalVisible,
      doClose: this.doClose,
      doSubmit: this.doSubmit,
      ...modalObj
    };
    const choosePersons =
      typeof this.state.choosePersons === 'string'
        ? JSON.parse(this.state.choosePersons)
        : this.state.choosePersons;

    const { status } = detailData || {};

    let titleLabel =
      APPROVAL_STATUS_NAME[status || String(detailData?.bizStatus)];

    const zhiDanState = detailData?.zhiDanState || '';
    const isShowZD = ['4', '5'].includes(zhiDanState);
    if (isShowZD) {
      titleLabel = ZHIDAN_STATUS_NAME[zhiDanState];
    }

    let colorClass = ApprovalColor[status || String(detailData?.bizStatus)];
    if (zhiDanState === ZHIDAN_STATUS.IsReturn) {
      colorClass = ApprovalColor[APPROVAL_STATUS.Reject];
    }

    return (
      <>
        <Card className={styles.detail}>
          <Card.Header
            className={styles.cardHeader}
            title={
              <div className={styles.header}>
                <div className={classnames(styles.icon, styles.desc)}>
                  <Avatar name={this.state.detailData?.bizUserName} />
                </div>

                <span title={title} className={styles.title}>
                  {title}
                </span>
                <span className={`${colorClass} ${styles.statusBox}`}>
                  {titleLabel}
                </span>
              </div>
            }
          >
          </Card.Header>
          <div className={styles.formDetail}>
            {/* <span className={styles.detailTitle}>详细信息</span> */}
            {/* {
              // parseApplyType === applyType.STUDENT_LABOUR_APPLY &&
              <>
                <ColumnText
                  name={'申报时间'}
                  value={this.state.detailData?.bizCrtTime}
                >
                </ColumnText>
                <ColumnText
                  name={'申报编号'}
                  value={this.state.detailData?.bizCode}
                >
                </ColumnText>
                {applyTypeFromUrl !== applyType.ONLINE_DOCUMENT_APPLY && (
                  <ColumnText
                    name={'流水号'}
                    value={
                      this.state.detailData?.serialNumber === '""'
                        ? '暂无'
                        : this.state.detailData?.serialNumber
                    }
                  >
                  </ColumnText>
                )}

                <ColumnText
                  name={'申报人'}
                  value={this.state.detailData?.bizUserName}
                >
                </ColumnText>
                <ColumnText
                  name={'申报人部门'}
                  value={this.state.detailData?.bizOrgName}
                >
                </ColumnText>
              </>
            } */}
            {this.renderForm()}
            {this.state.detailData?.taxAmount !== undefined && (
              <>
                <ColumnText
                  name={'本次计税(元)'}
                  isShowZero={this.state.detailData?.actualHairAmount > 0}
                  value={this.state.detailData?.taxAmount}
                >
                </ColumnText>
                <ColumnText
                  name={'实发金额(元)'}
                  value={this.state.detailData?.actualHairAmount}
                >
                </ColumnText>
              </>
            )}
          </div>
          {state.formData ? (
            <div className={styles.applyFormProcess}>
              {state?.detailData?.bizStatus === APPROVAL_STATUS.Draft ? (
                <ProcessSteps
                  setValidateMethod={this.setValidateMethod}
                  historyTask={state?.detailData?.historyTask || []}
                  form={props.form}
                  formData={state.formData}
                  formValues={this.state.formValues}
                  query={this.getSearchName()}
                  renderMode="detail"
                  choosePersons={choosePersons}
                />
              ) : (
                <ProcessList
                  srvTime={state.detailData?.srvTime}
                  className={styles.processList}
                  historyTask={state?.detailData?.historyTask || []}
                  renderMode="detail"
                />
              )}
              {this.checkPDFIsExit() && (
                <div
                  onClick={this.previewPDF}
                  className={styles.viewPdfStamp}
                  style={{ textAlign: 'center', color: '#2779ff' }}
                >
                  查看电子签章
                </div>
              )}
            </div>
          ) : null}
        </Card>
        {buttonOptions.length ? (
          <ButtonFooterDetail data={buttonOptions} />
        ) : (
          ''
        )}
        <ConfirmAndRefuseModal {...modalProps} />
        <VerificationCodeModal
          visible={verificationCodeModalVisible}
          handleModalClose={this.handleVerificationClose}
          sendVerificationCode={sendVerificationCode}
          checkVerificationCode={checkVerificationCode}
          handleSuccess={this.handleVerifiSuccess}
          title={'身份验证'}
        />
        {previewPdfVisible && (
          <PreviewPdf
            pdfUrl={pdfUrl}
            closePreviewPdf={() => {
              this.setState({ previewPdfVisible: false });
            }}
          />
        )}
      </>
    );
  }
}
const mapStateToProps = (state) => {
  return {
    userInfo: state.common?.userInfo
  };
};
// { common: { userInfo } }
export default connect(mapStateToProps)(
  createDOMForm({} as IApprovalModal)(ApprovalModal)
);
